define(function (require, exports, module) {

    var $ = require("jquery");

    var submit = $(".submit");
    var resultBox = $(".result");

    var threadsNum = 0;
    var loadingNum = 0;
    var gap = 10;
    var flag = false;

    var index = {

        init: function () {
            submit.bind("click", index.submit);
        },

        submit: function () {
            var threads = $("input[name='threads']").val();
            var url = $("input[name='url']").val();
            var cricle = $("input[name='cricle']").val();
            var expect = $("input[name='expect']").val();

            if (!threads || !url || !cricle || !expect) {
                return alert("请填写参数！~");
            }

            threads = parseInt(threads) * 100;
            threadsNum = threads;
            index.initResultBox();
            submit.unbind("click", index.submit);
            submit.bind("click", index.prevent);
            index.goon(threads / gap, url, cricle, expect);
        },

        prevent: function () {
            alert("性能测试中，请勿重复提交！~");
        },

        initResultBox: function () {
            resultBox.empty();

            var $process = $("<label>").text("第一轮测试中").addClass("process");
            var $p = $("<p>").append($process);

            var $loading = $("<label>").addClass("loading");
            $p.append($loading);

            var i = 0;
            loadingNum = setInterval(function () {
                i++;
                $loading.append(".");
                if (i == 6) {
                    i = 0;
                    $loading.empty();
                }
            }, 1000);

            resultBox.append($p);
            resultBox.append($("<table>"));

            var data = {
                sum: "线程总数",
                rate: "生成速率(/s)",
                avg: "平均响应时长(mm)",
                min: "最小响应时长(mm)",
                max: "最大响应时长(mm)",
                err: "错误量",
                errrate: "错误率"
            };
            index.insertData(data);
        },

        insertData: function (data) {
            var $tr = $("<tr>");
            $tr.append($("<td>").text(data.sum));
            $tr.append($("<td>").text(data.rate));
            $tr.append($("<td>").text(data.avg));
            $tr.append($("<td>").text(data.min));
            $tr.append($("<td>").text(data.max));
            $tr.append($("<td>").text(data.err));
            $tr.append($("<td>").text(data.errrate));
            $(".result table").append($tr);
        },

        goon: function (threads, url, cricle, expect) {
            $.ajax({
                url: "http.do?method=test",
                type: "post",
                dataType: "text",
                data: {
                    threads: threads,
                    url: url,
                    cricle: cricle
                },
                success: function (data) {
                    if (data == "err") {
                        alert("参数错误！~");
                        index.stop();
                        return;
                    }

                    data = $.parseJSON(data);
                    console.log(data);
                    data.sum = parseInt(data.sum) / cricle;
                    data.err = parseInt(data.err) / cricle;
                    data.avg = parseInt(data.avg);
                    var errrate = parseFloat(data.err) / parseFloat(data.sum);
                    data.errrate = (errrate * 100).toString().substring(0, 4) + "%";
                    index.insertData(data);

                    if (errrate >= 0.01 && confirm("错误率高于1%，是否终止测试？")) {
                        threads = threadsNum;
                    }

                    if (threads != threadsNum) {
                        if (data.avg >= expect) {
                            var last = threads - threadsNum / gap;
                            if (!flag) {
                                if (confirm("第一轮测试结果为：" + last + "-" + threads + "，是否继续开始第二轮？")) {
                                    flag = true;
                                    $(".process").text("第二轮测试中");
                                    gap = 100;
                                    index.goon(last, url, cricle, expect);
                                } else {
                                    index.stop();
                                }
                            } else {
                                alert("第二轮测试结果为：" + last + "-" + threads);
                                index.stop();
                            }
                        } else {
                            threads += threadsNum / gap;
                            index.goon(threads, url, cricle, expect);
                        }
                    } else {
                        index.stop();
                    }
                },
                error: function () {
                    alert("发生错误！~");
                }
            });
        },

        stop: function () {
            submit.bind("click", index.submit);
            submit.unbind("click", index.prevent);
            gap = 10;
            flag = false;
            clearInterval(loadingNum);
            $(".loading").remove();
        }

    };

    exports.init = function () {
        index.init();
    }

});